<template>
  <div class="wk-table-header">
    <div class="rightBox" :style="{ 'margin-top': !exportFieldsShow ? '-32px' : '-40px' }">
      <el-button v-if="exportFields.length > 0" class="collapse-button" :type="exportFieldsShow ? 'selected' : 'text'"
        @click="collapseHandle()">
        {{ exportFieldsShow ? '收起筛选' : '展开筛选' }}
        <i :class="['el-icon-arrow-up', { 'is-reverse': !exportFieldsShow }]" />
      </el-button>
      <el-button v-if="config.showFilterView" type="subtle" class="filter-button"
        :class="{ 'has-values': filterValidCount > 0 }" @click="showFilterClick">
        <svg-icon icon-class="filter" class="filters" @click.stop="showFilterClick(item)" />
        <span v-if="filterValidCount > 0" class="values-span" closable type="info">
          {{ filterValidCount}}
          <i class="el-icon-close" @click.stop="clearFilterVal(filterObj.form)" /> 
        </span>
      </el-button>

      <!-- <span class="switch-box" style="float: right;">
        <span :class="openScreen ? 'switch-item' : 'switch-item-select'" @click="switchOpenScreen()">
          <i class="el-icon-s-fold"></i>
        </span>
        <span :class="openScreen ? 'switch-item-select' : 'switch-item'" @click="switchOpenScreen()">
          <i class="el-icon-s-unfold"></i>
        </span>
      </span> -->

    </div>


    <filter-expand-fields v-if="exportFields.length > 0 && exportFieldsShow" :condition-type-fun="conditionTypeFun"
      :form="exportFields" :field-list="fieldList" @filter="exportFilter" @clear="clearFilterVal" />


    <!-- :crm-type="crmType" -->

    <!-- 高级筛选 -->
    <advanced-filters ref="advancedFilters" v-if="config.showFilterView" :field-list="fieldList"
      :dialog-visible.sync="filterShow" :dialogVisible.sync="filterShow" :obj="filterObj"
      :condition-type-fun="conditionTypeFun" :props="filterFormProps" @filter="handleFilter" :addType="addType" />
    <!-- :save-scene="!isSeas" -->

  </div>
</template>

<script>
/**
 * @description: todo
 * 选择产品 筛选场景隐藏 根据 tabs 数据源来控制
 *
 * 高级筛选
 * show-export 改为了 props
 * save-scene 改为了 props  搜索之后改为 props 逻辑
 *
 * 基础布局 WkFilterHeader
 * showSceneView 改为 tabSetShow
 *
 * props.ignoreFilterFields 兼容
 * $parent 兼容 直接控制父的方法
 *
 */

import { queryScene, queryListHead } from "@/api/customer/common";
import filterExpandFields from '../filterExpandFields'
import AdvancedFilters from '../AdvancedFilters'

import merge from '@/utils/merge'
import { isArray } from '@/utils/types'
import AdvancedFilterMixin from '@/mixins/AdvancedFilter'
import { objDeepCopy } from '@/utils'

const DefaultWkTableHeader = {
  showFilterView: true, // 控制是否展示高级筛选
  showExportFields: false // 展示外漏布局 仅指展开闭合
  // tabSetShow: false // 默认不展示场景
}

export default {
  // WkTableHeader
  name: 'TableHeaderFilters',

  components: {
    filterExpandFields,
    AdvancedFilters
  },

  mixins: [AdvancedFilterMixin],

  inheritAttrs: false,

  props: {
    props: Object, // TableHeader的辅助配置
    filterHeaderProps: Object, // 基础布局配置
    filterFormProps: Object, // 高级筛选配置
    sceneSetProps: Object, // 场景设置配置
    sceneCreateProps: Object, // 场景设置配置
    conditionTypeFun: Function, // 根据filed对象中的数据，校准条件。例如产品下的状态是select类型，需要更正为status
    fields: [Array, Function], // 直接提供数据 或者 提供一个返回promise 数据的方法
    addType: String,
  },

  data () {
    return {
      filterObj: { form: [], obj: [] }, // 筛选确定数据 form 是展示数组  obj 是上传数据
      exportFieldsShow: false, // 展示外露筛选
      fieldList: [], // 高级筛选字段
      filterShow: false, // 展示高级筛选
      sceneSetShow: false, // 展示场景设置
      openScreen: false,
      // addType: this.$GlobalStatus.tableType.Contacts,
    }
  },

  computed: {
    // 合并 props
    config () {
      return merge({ ...DefaultWkTableHeader }, this.props || {})
    },

    filterHeaderConfig () {
      return {
        // maxTabCount: this.sceneMaxCount,
        // searchPlaceholder: this.placeholder,
        tabSetShow: true,
        tabSetLabel: '场景设置',
        tabSetCommand: 'sceneSet',
        ...(this.filterHeaderProps || {})
      }
    },

    // 外露搜索字段
    exportFields () {
      if (this.filterObj.form) {
        console.log("formNONO===1111111=", this.filterObj.form.filter((item) => item.isOut === 1));
        return this.filterObj.form.filter((item) => item.isOut === 1)
      }
      return []
    },

    // 有条件的值
    filterValidCount () {
      const conditions = isArray(this.filterObj.obj) ? this.filterObj.obj : []
      // 滤掉无效值 5 6 为空 不为空 不需要提供values
      const hasValueConditions = conditions.filter(
        (item) =>
          (item.values && item.values.length > 0) || [5, 6].includes(item.type)
      )
      return hasValueConditions.length
    }
  },

  watch: {
    // 处理外露展示及其数据获取
    'config.showExportFields': {
      async handler (val) {
        // 如果展示外漏是true fieldList 是方法，需要理解触发获取数据
        // 默认需要获取一下高级筛选。保证页面根据有外露值正常展示
        if (
          this.config.showFilterView &&
          (!isArray(this.fieldList) || this.fieldList.length === 0)
        ) {
          this.exportFieldsShow = val
        }
      },
      immediate: true
    }
  },

  created () { },

  mounted () {
    // this.queryScene()
  },

  beforeDestroy () { },

  methods: {

    /* ------------------------ 基础展示组件 ------------------------ */
    /**
     * @description: 操作事件
     * @param {*}
     * @return {*}
     */
    filterHeaderHandle (commond, value) {
      if (commond === this.filterHeaderConfig.tabSetCommand) {
        this.sceneSetShow = true
      }
    },

    /* ------------------------ 外露筛选 ------------------------ */
    /**
     * 外露筛选折叠操作
     */
    collapseHandle (show) {
      const exportFieldsShow =
        show !== undefined ? show : !this.exportFieldsShow
      if (exportFieldsShow !== this.exportFieldsShow) {
        this.exportFieldsShow = exportFieldsShow
        //  true：是折叠不请求数据 更新table高度
        this.$emit(
          'event-change',
          'export-fields-collapse',
          this.exportFieldsShow
        )
      }
      // this.$emit('filter-change', {}, true)
      // this.updateFilterConfig()
    },

    /**
     * 外露筛选
     */
    exportFilter (data) {
      // 使用外露筛选  更新 obj 里的内容， form 的内容会双向联动
      this.filterObj.obj = data
      this.$emit('filter-change', data)
    },

    /**
     * 清空外露筛选值
     */
    clearFilterVal (list) {
      this.filterObj.obj = []
      // 下面方法 重置 form里的值
      this.resetAdvancedFilterFieldsValue(list)
      this.$emit('filter-change', [])
    },

    // /**
    //  * 更新style样式
    //  */
    // updateFilterConfig() {
    //   this.$parent.updateTableStyle({
    //     filterConfig: {
    //       exportFieldsShow: this.exportFieldsShow
    //     }
    //   })
    // },

    /* ------------------------ 高级筛选 ------------------------ */
    /**
     * 展示高级筛选
     */
    async showFilterClick (itemForm) {
      this.filterShow = true
      if (itemForm) {
        this.$refs.advancedFilters.addItem(itemForm);
      }
    },
    getFilterItem () {
      return {
        fieldName: '',
        name: '',
        formType: '',
        isOut: 0, // 外露
        condition: 'contains',
        type: 3,
        value: '',
        setting: [],
        typeOption: [],
        settingList: [],
        flowName: '', // 阶段名称
        settingName: '', // 流程名称
        address: {
          state: '',
          city: '',
          area: ''
        }
      }
    },
    /**
     * 高级筛选确定
     * isExport 是外露点击 不发送请求, 主要通知父更新高度
     * saveChecked 保存默认场景
     */
    handleFilter (form, isExport, fieldList) {
      this.filterObj = form
      this.fieldList = fieldList;
      if (isExport) {
        if (!this.exportFieldsShow) {
          // this.collapseHandle(true)
        }
      } else {
        this.filterShow = false
        // 保存场景
        if (form.saveChecked) {
          this.sceneCreateProps
            .saveRequest({
              // type: moduleType[this.crmType],
              isDefault: form.saveDefault ? 1 : 0,
              name: form.saveName,
              data: JSON.stringify(form.obj),
              ...this.sceneCreateProps.saveParams
            })
            .then((res) => {
              this.updateSceneList()
            })
            .catch(() => { })
        }
        this.$emit('filter-change', form.obj)
      }
    },

    /**
     * @description: 刷新场景
     * @param {*}
     * @return {*}
     */
    updateSceneList () {
      this.$emit('event-change', 'scene-refresh')
    },

    //按钮显示隐藏事件
    switchOpenScreen () {
      this.openScreen = !this.openScreen
      this.$emit('changeState', this.openScreen)
    },
  }
}
</script>

<style lang="scss" scoped>
.wk-table-header {
  .rightBox {
    float: right;

    .switch-box {
      background-color: #ebecf0;
      width: 64px;
      height: 32px;
      padding: 4px;
      margin-left: 10px;
      border-radius: 3px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .switch-item {
        height: 25px;
        width: 25px;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 3px;
      }

      .switch-item-select {
        height: 25px;
        width: 25px;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #fff;
        border-radius: 3px;
      }
    }
  }

  // 高级筛选
  .filter-button {
    background-color: rgba(0, 0, 0, 0.05);
    &.has-values {
      background-color: $--color-n30;
    }
  }

  // 有效值
  .values-span {
    margin-left: 2px;
    color: $--color-primary;
    background-color: $--color-n40;
    border-radius: $--border-radius-base;

    .el-icon-close {
      margin-right: 2px;
      font-size: 12px;
      color: $--color-black;
      cursor: pointer;

      &:hover {
        color: $--color-primary;
      }
    }
  }

  // 筛选展开闭合
  .collapse-button {
    padding-right: 12px;
    padding-left: 12px;

    .el-icon-arrow-up {
      transition: transform 0.3s;
    }

    .el-icon-arrow-up.is-reverse {
      transform: rotate(180deg);
    }
  }

  // 外露筛选
  .filter-export-fields {
    margin-top: 8px;
  }
}
</style>
